package com.hson.demo.base.crypter;

import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

/**
 * AES加解密方法
 * @author huangym3
 * @time 2016年5月5日 下午2:38:28
 */
public class CryptAES {

	private static final String AESTYPE = "AES/ECB/PKCS5Padding";

	public static String AES_Encrypt(String keyStr, String plainText) {
		byte[] encrypt = null;
		try {
			Key key = generateKey(keyStr);
			Cipher cipher = Cipher.getInstance(AESTYPE);
			cipher.init(Cipher.ENCRYPT_MODE, key);
			encrypt = cipher.doFinal(plainText.getBytes("utf-8"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new String(Base64.encodeBase64(encrypt));
	}

	public static String AES_Decrypt(String keyStr, String encryptData) {
		byte[] decrypt = null;
		try {
			Key key = generateKey(keyStr);
			Cipher cipher = Cipher.getInstance(AESTYPE);
			cipher.init(Cipher.DECRYPT_MODE, key);
			decrypt = cipher.doFinal(Base64.decodeBase64(encryptData));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new String(decrypt).trim();
	}

	private static Key generateKey(String key) throws Exception {
		try {
			SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "AES");
			return keySpec;
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}

	}

	public static void main(String[] args) {

		String keyStr = "UITN25LMUQC436IM";

		String plainText = "this is a string will be AES_Encrypt";

		String encText = AES_Encrypt(keyStr, plainText);
		String decString = AES_Decrypt(keyStr, encText);

		System.out.println(encText);
		System.out.println(decString);

		encText = AES_Encrypt("UITN25LMUQC436IMUITN25LMUQC436IM", plainText);
		decString = AES_Decrypt("UITN25LMUQC436IMUITN25LMUQC436IM", encText);
		System.out.println(encText);
		System.out.println(decString);

		
		System.out.println(AES_Encrypt("abcdefghijklmnop", "1234567890"));
		System.out.println(AES_Decrypt("abcdefghijklmnop", "SDHzzOe0O8cb2HVnOT/TuA=="));
		
		String str1 = "{\"appid\":\"wxbc20783e457e5fd2\"}";
//		"scope":"snsapi_login",
//		"redirect_uri":"http://micros.4000916916.com/ms_openwechat/wechat/1001/callback.ms",
//		"state":"b6c528dedf7511e584e30050569f4cfd",
//		"style":"black",
//		"href":"",
//		"authId":"1001",
//		"nonce":"e00c624affa611e5bd4a0050569f4cfd"
		
		
		System.out.println(AES_Encrypt("abcdefghijklmnop", str1));
		System.out.println(AES_Decrypt("abcdefghijklmnop", "xGUscqK7WmkjT4q1M/aDG3qkQ9m5D1UP6QHn3QrtfOA="));
	}
}